#include "maincontroller.h"

MainController::MainController()
{
    xml_parser_=new XmlToRecords();
    database_manager_=new DatabaseManager(this);

}

MainController::~MainController(){
    delete xml_parser_;
}

void MainController::loadConfig(QString filename)
{
    QFile file(filename);
    file.open(QFile::ReadOnly);

    QJsonParseError err;
    QJsonDocument doc=QJsonDocument::fromJson(file.readAll(),&err);

    if(err.error!=QJsonParseError::NoError){
        qDebug()<<"parse error:"<<err.errorString();
        return;
    }
    root_config_json_=doc.object();

    if(root_config_json_.contains("XmlParseConfig")){
        xml_parser_->loadConfig(root_config_json_.value("XmlParseConfig").toObject());
    }

    if(root_config_json_.contains("DatabaseConfig")){
        database_manager_->loadConfig(root_config_json_.value("DatabaseConfig").toObject());
    }

    ConfigEditor editor;
    editor.set_root_config_obj(root_config_json_);
    editor.setValue(QStringList() <<"XmlParseConfig"<<"keyAttr"<<"PWD"<< "Name","testName");

}

void MainController::readRecord(QString filename)
{
    QList<QMap<QString,QString>> record_list=xml_parser_->readFile(filename);
    int num=record_list.size();
    for(int i=0; i<num; ++i){
        if(database_manager_->table_name_list().size()>0)
            database_manager_->insertRecord(database_manager_->table_name_list().at(0),record_list.at(i));
    }
}

void MainController::set_root_config_json(QJsonObject obj)
{
    root_config_json_=obj;
}
